<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-left">
        <text class="header-title">农作物管理</text>
        
      </view>
    </view>
    
    <!-- 状态筛选 -->
    <view class="status-filter">
      <scroll-view scroll-x="true" class="filter-scroll" show-scrollbar="false">
        <view 
          v-for="(item, index) in statusFilters" 
          :key="index"
          class="filter-item"
          :class="{ active: currentStatusFilter === item.value }"
          @tap="filterByStatus(item.value)"
        >
          <text>{{ item.label }}</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 农作物列表 -->
    <scroll-view 
      scroll-y="true" 
      class="crops-list"
      @scrolltolower="loadMoreCrops"
      refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="crops.length > 0">
        <view 
          class="crop-item"
          v-for="crop in crops" 
          :key="crop._id"
          @tap="goToCropDetail(crop._id)"
        >
          <view class="crop-image">
            <image 
              :src="crop.image || '/static/images/default-crop.png'" 
              mode="aspectFill"
            ></image>
          </view>
          <view class="crop-info">
            <view class="crop-name-row">
              <text class="crop-name">{{ crop.name }}</text>
              <text class="crop-status" :class="getStatusClass(crop.status)">{{ getStatusText(crop.status) }}</text>
            </view>
            <view class="crop-details">
              <view class="detail-item">
                <uni-icons type="tag" size="14" color="#999999"></uni-icons>
                <text>{{ crop.crop_type }}</text>
              </view>
              <view class="detail-item">
                <uni-icons type="location" size="14" color="#999999"></uni-icons>
                <text>{{ crop.location }}</text>
              </view>
              <view class="detail-item">
                <uni-icons type="calendar" size="14" color="#999999"></uni-icons>
                <text>{{ formatDate(crop.plant_date) }}</text>
              </view>
            </view>
            <view class="crop-progress" v-if="crop.status === 0">
              <view class="progress-label">
                <text>生长进度</text>
                <text>{{ calculateGrowthDays(crop.plant_date) }}天</text>
              </view>
              <view class="progress-bar">
                <view 
                  class="progress-inner" 
                  :style="{ width: calculateGrowthProgress(crop.plant_date, crop.harvest_date) + '%' }"
                ></view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore">
          <text>加载中...</text>
        </view>
        <view class="load-more" v-else>
          <text>没有更多了</text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <image src="/static/images/empty-crops.png" mode="aspectFit"></image>
        <text>暂无农作物记录</text>
        <button class="add-btn" @tap="goToAddCrop">添加农作物</button>
      </view>
    </scroll-view>
    
    <!-- 添加按钮 -->
    <view class="fab-btn" @tap="goToAddCrop">
      <uni-icons type="plusempty" size="24" color="#ffffff"></uni-icons>
    </view>
    
   
    
    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopup" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text>筛选条件</text>
          <text class="close-btn" @tap="closeFilterPopup">关闭</text>
        </view>
        <view class="filter-section">
          <text class="filter-title">农作物类型</text>
          <view class="filter-options">
            <view 
              class="filter-tag"
              v-for="(type, index) in cropTypes" 
              :key="index"
              :class="{ active: filterOptions.type === type }"
              @tap="selectFilterType(type)"
            >
              <text>{{ type }}</text>
            </view>
          </view>
        </view>
        <view class="filter-section">
          <text class="filter-title">种植位置</text>
          <view class="filter-options">
            <view 
              class="filter-tag"
              v-for="(location, index) in locations" 
              :key="index"
              :class="{ active: filterOptions.location === location }"
              @tap="selectFilterLocation(location)"
            >
              <text>{{ location }}</text>
            </view>
          </view>
        </view>
        <view class="filter-buttons">
          <button class="reset-btn" @tap="resetFilters">重置</button>
          <button class="confirm-btn" @tap="applyFilters">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
/// <reference types="@dcloudio/types" />
import { ref, reactive, onMounted, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
// 导入uni-icons组件
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';

// 农作物列表
const crops = ref([]);
const isRefreshing = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = 10;

// 筛选状态
const statusFilters = [
  { label: '全部', value: -1 },
  { label: '种植中', value: 0 },
  { label: '已收获', value: 1 },
  { label: '已废弃', value: 2 }
];
const currentStatusFilter = ref(-1);


// 筛选选项
const cropTypes = ['全部', '蔬菜', '水果', '粮食', '经济作物', '药材', '其他'];
const locations = ['全部', '1号大棚', '2号大棚', '3号大棚', '露天农田', '实验区'];
const filterOptions = reactive({
  type: '全部',
  location: '全部'
});

// 获取农作物列表
const fetchCrops = async (reset = false) => {
  if (reset) {
    page.value = 1;
    crops.value = [];
    hasMore.value = true;
  }
  
  try {
    // 构建查询条件
    const query = {
      page: page.value,
      pageSize: pageSize
    };
    
    // 添加筛选条件
    if (currentStatusFilter.value >= 0) {
      query.status = currentStatusFilter.value;
    }
    
    if (filterOptions.type !== '全部') {
      query.crop_type = filterOptions.type;
    }
    
    if (filterOptions.location !== '全部') {
      query.location = filterOptions.location;
    }
    
    // 调用云函数获取农作物列表
    const { result } = await uniCloud.callFunction({
      name: 'crop',
      data: {
        action: 'list',
        data: query
      }
    });
    
    if (result.code === 200) {
      if (reset) {
        crops.value = result.data.list;
      } else {
        crops.value = [...crops.value, ...result.data.list];
      }
      
      // 判断是否还有更多数据
      const { pagination } = result.data;
      hasMore.value = crops.value.length < pagination.total;
      
      // 更新页码
      if (hasMore.value) {
        page.value++;
      }
    } else {
      uni.showToast({
        title: result.msg,
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取农作物列表失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
  } finally {
    if (isRefreshing.value) {
      isRefreshing.value = false;
    }
  }
};

// 刷新农作物列表
const refreshCrops = () => {
  fetchCrops(true);
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  refreshCrops();
};

// 加载更多
const loadMoreCrops = () => {
  if (hasMore.value) {
    fetchCrops();
  }
};

// 按状态筛选
const filterByStatus = (status) => {
  if (currentStatusFilter.value !== status) {
    currentStatusFilter.value = status;
    refreshCrops();
  }
};


// 显示筛选弹窗
const filterPopup = ref(null);


// 关闭筛选弹窗
const closeFilterPopup = () => {
  filterPopup.value.close();
};

// 选择筛选类型
const selectFilterType = (type) => {
  filterOptions.type = type;
};

// 选择筛选位置
const selectFilterLocation = (location) => {
  filterOptions.location = location;
};

// 重置筛选
const resetFilters = () => {
  filterOptions.type = '全部';
  filterOptions.location = '全部';
};

// 应用筛选
const applyFilters = () => {
  closeFilterPopup();
  refreshCrops();
};

// 跳转到农作物详情
const goToCropDetail = (id) => {
  uni.navigateTo({
    url: `/pages/crops/detail?id=${id}`
  });
};

// 跳转到添加农作物
const goToAddCrop = () => {
  uni.navigateTo({
    url: '/pages/crops/edit'
  });
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 计算生长天数
const calculateGrowthDays = (plantDate) => {
  if (!plantDate) return 0;
  const now = new Date();
  const start = new Date(plantDate);
  const diffTime = Math.abs(now - start);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays;
};

// 计算生长进度
const calculateGrowthProgress = (plantDate, harvestDate) => {
  if (!plantDate || !harvestDate) return 0;
  
  const now = new Date();
  const start = new Date(plantDate);
  const end = new Date(harvestDate);
  
  // 已经超过收获日期
  if (now > end) return 100;
  
  const totalDuration = end - start;
  const currentProgress = now - start;
  
  return Math.min(100, Math.round((currentProgress / totalDuration) * 100));
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '种植中';
    case 1:
      return '已收获';
    case 2:
      return '已废弃';
    default:
      return '未知';
  }
};

// 获取状态类名
const getStatusClass = (status) => {
  switch (status) {
    case 0:
      return 'status-growing';
    case 1:
      return 'status-harvested';
    case 2:
      return 'status-abandoned';
    default:
      return '';
  }
};

// 页面加载时初始化数据
onMounted(() => {
  // 初始加载时只调用一次fetchCrops
  fetchCrops();
});

// 页面显示时刷新数据（从其他页面返回时）
onShow(() => {
  // 只有当不是首次加载时才刷新数据
  if (crops.value.length > 0) {
    refreshCrops();
  }
});
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding-bottom: 20px;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  width: 100%;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.farm-selector {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.farm-selector text:first-child {
  font-size: 14px;
  color: #666666;
  margin-right: 5px;
}

.header-right {
  display: flex;
}

.icon-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10px;
}

/* 状态筛选 */
.status-filter {
  background-color: #ffffff;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.filter-scroll {
  white-space: nowrap;
}

.filter-item {
  display: inline-block;
  padding: 6px 15px;
  margin: 0 5px;
  border-radius: 20px;
  background-color: #f5f5f5;
}

.filter-item text {
  font-size: 14px;
  color: #666666;
}

.filter-item.active {
  background-color: #4CAF50;
}

.filter-item.active text {
  color: #ffffff;
}

/* 农作物列表 */
.crops-list {
  flex: 1;
  padding: 10px;
}

.crop-item {
  display: flex;
  margin-bottom: 10px;
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
}

.crop-image {
  width: 100px;
  height: 100px;
}

.crop-image image {
  width: 100%;
  height: 100%;
}

.crop-info {
  flex: 1;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.crop-name-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.crop-name {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.crop-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.status-growing {
  background-color: #E3F2FD;
  color: #2196F3;
}

.status-harvested {
  background-color: #E8F5E9;
  color: #4CAF50;
}

.status-abandoned {
  background-color: #FFEBEE;
  color: #F44336;
}

.crop-details {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 5px;
}

.detail-item text {
  font-size: 14px;
  color: #666666;
  margin-left: 5px;
}

.crop-progress {
  margin-top: auto;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.progress-label text {
  font-size: 12px;
  color: #999999;
}

.progress-bar {
  height: 4px;
  background-color: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.progress-inner {
  height: 100%;
  background-color: #4CAF50;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 15px 0;
}

.load-more text {
  font-size: 14px;
  color: #999999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.empty-state image {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
}

.empty-state text {
  font-size: 16px;
  color: #999999;
  margin-bottom: 20px;
}

.add-btn {
  background-color: #4CAF50;
  color: #ffffff;
  font-size: 14px;
  padding: 8px 20px;
  border-radius: 20px;
}

/* 悬浮添加按钮 */
.fab-btn {
  position: fixed;
  right: 20px;
  bottom: 90px;
  width: 60px;
  height: 60px;
  border-radius: 30px;
  background-color: #4CAF50;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 999;
}

/* 弹窗样式 */
.popup-content {
  background-color: #ffffff;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.popup-header text:first-child {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.close-btn {
  font-size: 14px;
  color: #999999;
}

/* 农场列表 */
.farm-list {
  max-height: 300px;
}

.farm-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.farm-item text:first-child {
  font-size: 16px;
  color: #333333;
}

/* 筛选部分 */
.filter-section {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-title {
  font-size: 16px;
  color: #333333;
  margin-bottom: 10px;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
}

.filter-tag {
  padding: 6px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.filter-tag text {
  font-size: 14px;
  color: #666666;
}

.filter-tag.active {
  background-color: #E8F5E9;
}

.filter-tag.active text {
  color: #4CAF50;
}

.filter-buttons {
  display: flex;
  padding: 15px;
}

.reset-btn, .confirm-btn {
  flex: 1;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 4px;
  font-size: 16px;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666666;
  margin-right: 10px;
}

.confirm-btn {
  background-color: #4CAF50;
  color: #ffffff;
}

/* 确保uni-icons组件正确显示 */
.uni-icons {
  font-family: uniicons !important;
  text-decoration: none;
  text-align: center;
}
</style> 